<template>
  <div id="testPaper">
    <Breadcrumb content="核算要素" />
    <div class="bodyContent">
      <Splitpanes class="area">
        <Pane size="30">
          <vxe-toolbar perfect>
            <template #buttons>
              <vxe-input style="width: 180px" v-model="searchForm.keyWord" type="search" clearable class="vxeInputSearch" placeholder="关键字查询" @clear="getCalcElementList" @search-click="getCalcElementList"></vxe-input>
              <vxe-button type="text" icon="vxe-icon-refresh" class="button-blue" content="刷新" @click="getCalcElementList" :loading="showLoading"></vxe-button>
              <vxe-button type="text" class="button-blue" icon="vxe-icon-square-plus" content="新建" @click="add()"></vxe-button>
              <vxe-button type="text" icon="vxe-icon-delete" class="button-red" content="删除" @click="handleDelete"></vxe-button>
            </template>
          </vxe-toolbar>
          <div class="calcItemtableBox">
            <vxe-table ref="calcElementTableRef" :loading="showLoading" @current-change="currentChangeEvent" class="mytable-scrollbar" border align="left" height="auto" :keep-source="true" :data="calcItemList" :row-config="{ isCurrent: true, isHover: true }" resizable show-overflow>
              <vxe-column type="checkbox" align="center" width="26"></vxe-column>
              <vxe-column type="seq" title="序号" align="center" width="30"></vxe-column>
              <vxe-column field="elementCode" title="编码" width="60"></vxe-column>
              <vxe-column field="itemId" title="核算表单" width="60"></vxe-column>
              <vxe-column field="elementName" title="名称"></vxe-column>
              <vxe-column field="isEnable" title="是否启用" width="50">
                <template #default="{ row }">
                  <el-tag size="small"> {{ row.isEnable === 0 ? '否' : '是' }}</el-tag>
                </template>
              </vxe-column>
              <vxe-column field="calcStatement" title="计算语句"> </vxe-column>
              <vxe-column field="seq" title="顺序" width="50"> </vxe-column>
              <vxe-column field="remake" title="备注"> </vxe-column>
            </vxe-table>
          </div>
        </Pane>
        <Pane size="70">
          <el-tabs type="border-card"  v-model="activeName">
            <el-tab-pane label="基本信息" name="first">
              <el-scrollbar style="height: 100%">
                <el-form ref="calcElementFormRef" :model="calcElementForm" :rules="calcElementFormRules" label-width="100px" class="form-input-m" inline-message>
                  <el-form-item label="编码" prop="elementCode">
                    <el-input v-model="calcElementForm.elementCode" placeholder="编码" clearable></el-input>
                  </el-form-item>
                  <el-form-item label="核算要素" prop="elementName"> <el-input v-model="calcElementForm.elementName" placeholder="核算要素" clearable></el-input> </el-form-item>
                  <el-form-item label="是否启用" prop="isEnable">
                    <vxe-switch v-model="calcElementForm.isEnable" size="small" open-label="是" close-label="否" :open-value="1" :close-value="0"></vxe-switch>
                  </el-form-item>
                  <el-form-item label="顺序" prop="seq">
                    <el-input-number v-model="calcElementForm.seq" :min="1" :max="1000" />
                  </el-form-item>
                  <el-form-item label="备注" prop="remake">
                    <el-input v-model="calcElementForm.remake" :rows="6" type="textarea" placeholder="备注" clearable style="margin-right: 10px"></el-input>
                  </el-form-item>

                  <el-form-item class="form-footer">
                    <template #default>
                      <el-button type="primary" v-loading="saveLoading" @click="save()">保存</el-button>
                      <el-button type="default" @click="add()">重置</el-button>
                    </template>
                  </el-form-item>
                </el-form>
              </el-scrollbar>
            </el-tab-pane>
            <el-tab-pane label="计算语句" name="second">
              <el-form ref="calcSentenceRef" :model="calcElementForm"  :rules="calcSentenceRules" inline-message>
              <el-form-item prop="databaseId" style="margin-bottom:0;">
              <div class="dataSource">
                <span>数据源：</span>
                <el-select v-model="calcElementForm.databaseId" @change="dabaBaseChange" placeholder="数据源类型" style="width: 200px">
                  <el-option v-for="item in calcDataBaseList" :key="item.id" :label="item.databaseName" :value="item.id" />
                </el-select>
              </div>
              </el-form-item>
              <Splitpanes :style="{height: useSize === 'small' ? 'calc(100% - 24px - 15px - 5px)' : useSize === 'default' ? 'calc(100% - 32px - 15px - 5px)' : 'calc(100% - 40px - 15px - 5px)'}">
                <Pane size="25">
                  <el-scrollbar class="dataSourceLeft">
                    <el-checkbox-group v-model="dataBaseTableList">
                      <el-checkbox v-for="(item, index) in tableNamesOptions" :key="index" :label="item.TABLE_NAME" :value="item.TABLE_NAME" @change="checkboxTableChange(item.TABLE_NAME)" size="default" />
                    </el-checkbox-group>
                  </el-scrollbar>
                </Pane>
                <Pane size="75">
                  <Splitpanes horizontal>
                    <Pane size="35">
                      <el-scrollbar class="dataSourceTableCard">
                        <el-card v-for="(table, index) in checkTableList" :key="index" class="tableCard">
                          <template #header>
                            <div class="card-header ellipsis">
                              <el-tooltip
                              class="box-item"
                              effect="dark"
                              :content="table.name"
                              placement="top-start"
                            >
                              <span>{{ table.name }}</span>
                              </el-tooltip>
                            </div>
                          </template>
                          <el-scrollbar>
                            <el-checkbox-group v-model="table.checkColumns">
                              <el-checkbox v-for="(column, index) in table.columns" :key="index" :label="column.columnName" :value="column.columnName" @change="pushStateList(table.name, column)" class="cardBodyItem" />
                            </el-checkbox-group>
                          </el-scrollbar>
                        </el-card>
                      </el-scrollbar>
                    </Pane>
                    <Pane size="35">
                      <el-scrollbar style="height: 100%">
                        <vxe-table ref="calcElementStateRef" @current-change="currentChangeEvent" class="mytable-scrollbar" border align="left" height="auto" :keep-source="true" :data="stateList" :row-config="{ isCurrent: true, isHover: true }" resizable show-overflow>
                          <vxe-column field="column" align="center" title="列" width="26"></vxe-column>
                          <vxe-column field="alias" title="别名" align="center" width="30"></vxe-column>
                          <vxe-column field="tableName" title="表" width="60"></vxe-column>
                          <vxe-column field="output" title="是否输出" width="60"></vxe-column>
                          <vxe-column field="orderType" title="排序类型"></vxe-column>
                          <vxe-column field="order" title="排序顺序"></vxe-column>
                          <vxe-column field="filter" title="筛选器"></vxe-column>
                          <vxe-column field="or1" title="或者 "></vxe-column>
                        </vxe-table>
                      </el-scrollbar>
                    </Pane>
                    <Pane size="35">
                      <el-form-item prop="calcStatement">
                        <el-input type="textarea" :rows="9" v-model="calcElementForm.calcStatement" placeholder="计算语句" @click="handleInputBlur($event)" clearable style="margin-right: 10px"></el-input>
                      </el-form-item>
                      <el-form-item class="form-footer">
                        <template #default>
                          <el-button type="primary" v-loading="saveSentenceLoading" @click="saveSentence()">保存</el-button>
                          <el-tag type="primary" style="margin-left: 5px" @click="insertPageColumn('@统计日期(起)')"> @统计日期(起)</el-tag>
                          <el-tag type="primary" style="margin-left: 5px" @click="insertPageColumn('@统计日期(止)')"> @统计日期(止)</el-tag>
                          <el-tag type="primary" style="margin-left: 5px" @click="insertPageColumn('@员工工号')"> @员工工号</el-tag>
                          <!-- <el-button type="primary" v-loading="testConnectionLoading" @click="testConnection()">测试SQL</el-button> -->
                        </template>
                      </el-form-item>
                    </Pane>
                  </Splitpanes>
                </Pane>
              </Splitpanes>
            </el-form>
            </el-tab-pane>
          </el-tabs>
        </Pane>
      </Splitpanes>
    </div>
  </div>
</template>

<script setup lang="ts">
// 引入组件区 ==========
import { ref, reactive, getCurrentInstance, onMounted } from 'vue';
import Breadcrumb from '@/components/Breadcrumb.vue';
import { Splitpanes, Pane } from 'splitpanes';
import { VxeMessage, VxeNotifyType } from '@/utils/CommonMessage'; //提示信息
// import { getChartList } from '@/utils/ChartMenu'; //提示信息

// 定义变量区 ==========
let { proxy }: any = getCurrentInstance();
//根据关键字搜索
let searchForm = reactive({
  keyWord: ''
});
const calcItemList = reactive([]); //表格数据
let showLoading = ref(false); //表格加载状态
const calcDataBaseList = reactive([]);

const activeName = ref('first');

//右侧基本信息表单数据
const calcElementForm = reactive({
  id: '',
  itemId: '',
  elementCode: '',
  elementName: '',
  databaseId: '',
  tableName: '',
  isEnable: 0,
  calcStatement: '',
  seq: 0,
  remake: ''
});
// 基本信息表单 校验规则
let calcElementFormRules = {
  elementCode: [
    {
      required: true,
      message: '请输入编码',
      trigger: 'blur'
    }
  ],
  elementName: [
    {
      required: true,
      message: '请输入核算要素',
      trigger: 'blur'
    }
  ],
  isEnable: [
    {
      required: true,
      message: '请选择是否启用',
      trigger: 'blur'
    }
  ]
}

// 计算语句tab的校验规则
let calcSentenceRules = {
  databaseId:[
  {
      required: true,
      message: '请选择数据源',
      trigger: 'blur'
    }
  ],
  calcStatement:[
  {
      required: true,
      message: '请输入计算语句',
      trigger: 'blur'
    }
  ]
}

let testConnectionLoading = ref(false); //表单保存状态
let saveLoading = ref(false); //基本信息表单保存状态
let saveSentenceLoading = ref(false);//计算语句tab 保存状态
let tableNamesOptions = reactive([]);
let cursorIndex = ref(0);
const dataBaseTableList = reactive([]);
let checkTableList = reactive([]);

let useSize = ref(localStorage.getItem('uiSize') || 'small') ;//监听页面尺寸变化 对于elePlus
let stateList = reactive([]);

// 方法定义区 =====================================
onMounted(() => {
  getCalcElementList();
  getCalcDataBaseList();
});

// 获取左侧列表信息
function getCalcElementList() {
  calcItemList.length = 0;
  showLoading.value = true;
  const url = '/wk/calc/element/getCalcElementList';
  proxy.$http
    .get(url, { params: { keyWord: searchForm.keyWord } })
    .then((res: any) => {
      if (res.data && res.data.length > 0) {
        calcItemList.push(...res.data);
        currentChangeEvent({ row: calcItemList[0] });
        const $xTable = proxy.$refs.calcElementTableRef as any;
        if ($xTable) {
          $xTable.setCurrentRow(calcItemList[0]);
        }
        showLoading.value = false;
      }
    })
    .catch((err: any) => {
      showLoading.value = false;
      proxy.$alert(err, '提示');
    });
}

// 获取数据源字典
function getCalcDataBaseList() {
  calcDataBaseList.length = 0;
  const url = '/wk/calc/database/getDataBaseList';
  proxy.$http
    .get(url, { params: { keyWord: searchForm.keyWord } })
    .then((res: any) => {
      if (res.data) {
        calcDataBaseList.push(...res.data);
      }
    })
    .catch((err: any) => {
      proxy.$alert(err, '提示');
    });
}
//点击表格当前行 数据变化
function currentChangeEvent(row: any) {
  add(); //表格当前行变化时 先重置
  Object.assign(calcElementForm, row.row);
}

// 添加
function add() {
  Object.keys(calcElementForm).forEach((key) => {
    switch (typeof calcElementForm[key]) {
      case 'string':
        calcElementForm[key] = '';
        break;
      case 'number':
        //适用于顺序
        calcElementForm[key] = calcItemList.length + 1;
        break;
    }
  });
  proxy.$refs.calcElementFormRef.resetFields();//清空基本信息表单校验
  proxy.$refs.calcSentenceRef.resetFields();//清空计算语句tab页签校验
}

// 保存
function save() {
  saveLoading.value = true;
  let url = '';
  if (calcElementForm.id == '' || calcElementForm.id == null || calcElementForm.id == undefined) {
    url = '/wk/calc/element/addCalcElement';
  } else {
    url = '/wk/calc/element/editCalcElement';
  }
  const el: any = proxy.$refs.calcElementFormRef;//基本信息表单校验
  if (!el) return;
  el.validate((valid: any) => {
    if (!valid) {
      saveLoading.value = false;
      return false;
    }
    proxy.$http
      .post(url, calcElementForm)
      .then((res: any) => {
        VxeMessage(res.status.msg, VxeNotifyType.success);
        getCalcElementList();
        saveLoading.value = false;
      })
      .catch((err: any) => {
        VxeMessage(err, VxeNotifyType.error);
        saveLoading.value = false;
      });
  });
}

// 计算语句 保存
function saveSentence() {
  saveSentenceLoading.value = true;
  let url = '';
  if (calcElementForm.id == '' || calcElementForm.id == null || calcElementForm.id == undefined) {
    url = '/wk/calc/element/addCalcElement';
  } else {
    url = '/wk/calc/element/editCalcElement';
  }
  const elSentence:any = proxy.$refs.calcSentenceRef;//计算语句tab校验
  if (!elSentence) return;
  elSentence.validate((valid: any) => {
    if (!valid) {
      saveSentenceLoading.value = false;
      return false;
    }
    proxy.$http
      .post(url, calcElementForm)
      .then((res: any) => {
        VxeMessage(res.status.msg, VxeNotifyType.success);
        getCalcElementList();
        saveSentenceLoading.value = false;
      })
      .catch((err: any) => {
        VxeMessage(err, VxeNotifyType.error);
        saveSentenceLoading.value = false;
      });
  });
}
// 删除
function handleDelete() {
  const $xTable = proxy.$refs.calcElementTableRef as any;
  const selectRows = $xTable.getCheckboxRecords();
  if (selectRows.length <= 0) {
    VxeMessage('请先选中要删除的项', VxeNotifyType.warning);
    return;
  }
  proxy
    .$confirm('确定删除此项？', '提示', {
      cancelButtonClass: 'cancel-button',
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    .then((type) => {
      if (type === 'confirm') {
        let ids = selectRows.map((item) => item.id);
        const url = '/wk/calc/element/deleteCalcElement';
        proxy.$http
          .post(url, ids)
          .then((res: any) => {
            if (res.status.code === 1) {
              VxeMessage('删除成功', VxeNotifyType.success);
              getCalcElementList();
            } else {
              VxeMessage('删除失败', VxeNotifyType.error);
            }
          })
          .catch((err) => {
            VxeMessage(err.response.data.status.msg, VxeNotifyType.error);
          });
      }
    });
}

// 测试数据库连接
function testConnection() {
  testConnectionLoading.value = true;
  let url = '/wk/calc/database/testDatabaseConnection';
  let dataBaseForm = calcDataBaseList.find((item) => item.id === calcElementForm.databaseId);
  dataBaseForm.sql = calcElementForm.calcStatement;
  console.log('dataBaseForm', dataBaseForm);
  proxy.$http
    .post(url, dataBaseForm)
    .then((res: any) => {
      if (res.status.code === 1) {
        VxeMessage('sql执行成功', VxeNotifyType.success);
      } else {
        VxeMessage('sql执行失败，请检查sql语句是否正确', VxeNotifyType.error);
      }
      testConnectionLoading.value = false;
    })
    .catch((err: any) => {
      VxeMessage(err, VxeNotifyType.error);
      testConnectionLoading.value = false;
    });
}

// 选择数据源查询数据库中的表名
function dabaBaseChange() {
  tableNamesOptions.length = 0;
  const url = '/wk/calc/element/findTableNamesByDataBase';
  proxy.$http
    .get(url, { params: { dataBaseName: 'SYSTEM_LIS' } })
    .then((res: any) => {
      if (res.data) {
        tableNamesOptions.push(...res.data);
      }
    })
    .catch((err: any) => {
      proxy.$alert(err, '提示');
    });
}

// 选中表名事件
function checkboxTableChange(tableName: any) {
  dataBaseTableList.push(tableName);
  // checkTableList.length = 0;
  let obj = {
    name: tableName,
    columns: []
  };
  const url = '/wk/calc/element/findColumnsByTableName';
  proxy.$http
    .get(url, { params: { tableName: tableName } })
    .then((res: any) => {
      if (res.data) {
        obj.columns.push(...res.data);
        checkTableList.push(obj);
      }
    })
    .catch((err: any) => {
      proxy.$alert(err, '提示');
    });
}

// 插入条件集合
function pushStateList(tableName: any, column: any) {
  let stateInfo = {
    column: column.columnName,
    alias: '',
    tableName: tableName,
    output: '',
    orderType: '',
    order: '',
    filter: '',
    or1: ''
  };
  stateList.push(stateInfo);
}

// 鼠标点击事件
function handleInputBlur(e) {
  cursorIndex.value = e.srcElement.selectionStart;
}
// 在鼠标点击位置插入字段值
function insertPageColumn(tag) {
  if (cursorIndex.value) {
    let pageColumnStr = calcElementForm.calcStatement;
    let resultPageColumnStr = '';
    if (pageColumnStr.length <= cursorIndex.value) {
      resultPageColumnStr = pageColumnStr + "'" + tag + "'";
    } else {
      let s1 = pageColumnStr.substring(0, cursorIndex.value);
      let s2 = pageColumnStr.substring(cursorIndex.value, pageColumnStr.length);
      resultPageColumnStr = s1 + "'" + tag + "'" + s2;
    }
    calcElementForm.calcStatement = resultPageColumnStr;
  }
}
</script>

<style lang="scss" scoped>
#testPaper {
  height: 100%;
  .bodyContent {
    height: calc(100% - 60px);
    .area {
      background-color: $base-white;
      // 附加按钮间距
      .button-blue,
      .button-red {
        margin: 5px 0 5px 5px;
      }
      .calcItemtableBox {
        height: calc(100% - 40px);
      }
      .el-tabs {
        height: 100%;
        :deep(.el-tabs__content) {
          padding: 0;
          height: calc(100% - 39px);
          #pane-first {
            padding: 15px;
            height: calc(100% - 30px);
          }
          #pane-second {
            padding-top: 15px;
            height: calc(100% - 15px);
            .el-form {
              height: 100%;
            }
            .dataSource {
              width: 100%;
              box-sizing: border-box;
              padding: 0 15px 15px 15px;
              border-bottom: 5px solid #f1f2f6;
            }
            .dataSourceLeft {
              padding: 10px;
              width: calc(100% - 20px);
              height: calc(100% - 20px);
            }
            .dataSourceTableCard {
              height: 100%;
              .tableCard {
                max-width: 225px;
                max-height: 200px;
                height: 200px;
                display: inline-block;
                margin: 5px;
                .el-card__header {
                  padding: 10px 15px;
                  text-align: center;
                  .card-header {
                    width:200px;
                    overflow: hidden;
                    text-overflow: ellipsis;
                    white-space: nowrap;
                  }
                }
                .el-card__body {
                  padding: 0;
                  height: calc(100% - 37px);
                  .cardBodyItem {
                    margin: 10px;
                  }
                }
              }
            }
            .el-checkbox {
              display: block;
            }
          }
        }
      }
    }
  }
}
</style>
